const fs = require('fs')
const path = require('path')
const glob = require('glob')
const {
  resolve,
  isCore,
  baseUrl,
  prefix,
  isDiy
} = require('./utils')
const themeConfig = resolve('src/service/config.js')
const {
  themeId
} = require(themeConfig)
console.info('alasjg-web项目', isCore)
const superagent = require('superagent')
const isPc=true
const suffix = isPc ? 'vue' : 'nvue'


function getComponents(type) {
  console.info('导入组件目录：',type)
  const regDir = resolve('src', type)

  if (!fs.existsSync(regDir)) {
    return []
  }

  const files = glob.sync(`${regDir}/**/index.{vue,nvue}`)
  return files.map(file => {
    const componentPath = path.relative(regDir, file)
      .replace(/\\/g, '/')
      .replace(`/index.vue`, '')
      .replace(`/index.nvue`, '')
    const componentName = componentPath.replace(/^.*\//, '')
    const componentUpperName = componentName
      .replace(/-(\w)/g, (match, $1) => $1.toUpperCase())

    return {
      path: componentPath,
      name: componentName,
      upperName: componentUpperName
    }
  })
}


module.exports = async () => {
  var maxCount = 1
  var totalCount = 0
  if (isDiy) {
    maxCount = 1
  }
  console.log('开始更新组件引用',isPc)
  if (isPc === true) {
    const tplPath = resolve('src/main.tpl.js')
    if (!fs.existsSync(tplPath)) {
      console.warn('模板文件 main.tpl.js 不存在')
      return
    }

    const typeEnum = ['components', 'archives','elements', 'admins', 'v-data','webs']
    const tplContent = fs.readFileSync(tplPath).toString()
    const mainPath = resolve('src/main.js')


    let globalComponents = ''

    typeEnum.forEach(type => {
      getComponents(type).forEach(component => {
        var count = 0
        for (var i = 0; i < component.path.length; i++) {
          if (component.path[i] === '/') {
            count++
          }
        }
        if (count <= maxCount) {
          globalComponents +=
            `import ${component.upperName} from '@/${type}/${component.path}/index.${suffix}'\n`
          console.info('自动构建main.js中的组件', component.path)
          totalCount++
        }

      })
    })

    typeEnum.forEach(type => {
      getComponents(type).forEach(component => {
        var count = 0
        for (var i = 0; i < component.path.length; i++) {
          if (component.path[i] === '/') {
            count++
          }
        }
        if (count <= maxCount) {
          globalComponents += `Vue.component('${component.name}', ${component.upperName})\n`
        }
      })
    })

    const mainContent = tplContent.replace('/* 5ug auto-import */', globalComponents)
    fs.writeFileSync(mainPath, mainContent)
  }


}
